import * as fs from "fs";
import * as https from "https";
import * as http from "http";
import {ipcMain} from "electron";

const AdmZip = require("adm-zip");

export type DownloadFileProgress = {
    total: number,
    current: number
}

export type DownloadFileParam = {
    url: string,
    path: fs.PathLike,
    success?: () => void,
    error?: () => void,
    progress?: (progress: DownloadFileProgress, file: fs.WriteStream, request: http.ClientRequest, response: http.IncomingMessage) => void
}

export type DownloadParam = DownloadFileParam;

class FileUtil {
    downloadFile({url, path, success, error, progress}: DownloadFileParam) {
        const file = fs.createWriteStream(path);
        const request = https.get(url, (response) => {
            if (response.statusCode === 302) {
                // 获取重定向的地址
                const redirectUrl = response.headers.location;
                if (redirectUrl) {
                    // 手动重定向
                    this.downloadFile({
                        url: redirectUrl,
                        path: path,
                        success: success,
                        progress: progress
                    });
                }
                return;
            }
            if (response.statusCode !== 200) {
                console.error(`Request failed. Status Code: ${response.statusCode}`);
                file.end();
                file.close();
                file.destroy();
                fs.unlinkSync(path);
                error && error();
                return;
            }
            let totalBytes = parseInt(String(response.headers['content-length']), 10);

            ipcMain.on('closeReleaseDownload', () => {
                file.end();
                file.close();
                file.destroy();
                fs.unlinkSync(path);
                response.destroy();
                request.destroy()
            })

            response.on('data', chunk => {
                file.write(chunk);
                progress && progress({
                    total: totalBytes,
                    current: chunk.length
                }, file, request, response);
            })

            response.on('end', () => {
                file.end();
                console.log('下载完成');
                success && success();
            })
            // response.pipe(file);
            // file.on('finish', () => {
            //     file.close();
            //     resolve(dest);
            // });
        }).on('error', (err) => {
            file.end();
            file.close();
            file.destroy();
            fs.unlinkSync(path); // 删除已创建的不完整文件
            error && error();
            console.error(`Error occurred: ${err.message}`);
        });
    }

    download({url, path, error, success, progress}: DownloadParam) {
        try {
            this.downloadFile({
                url,
                path,
                success,
                error,
                progress
            });
        } catch (e) {
            fs.unlinkSync(path);
            error && error();
            console.error('下载失败：', e);
        }
    }

    unzip(filePath: fs.PathLike, outPath: fs.PathLike) {
        try {
            const admZip = new AdmZip(filePath);
            admZip.extractAllTo(outPath);
            console.log("解压成功")
            return true;
        } catch (e) {
            console.log("解压失败", e);
            return false;
        }
    }
}

export default new FileUtil();
